package com.mspbots.sync.callback.services.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.sync.BaseGenericService;
import com.mspbots.sync.callback.model.CallbackAction;
import com.mspbots.sync.callback.model.CallbackMessage;
import com.mspbots.sync.callback.services.NoticeService;
import com.mspbots.sync.model.TicketOnly;
import com.mspbots.sync.wise.service.TicketEntryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.sync.callback.WiseCallBackService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/12
 */
@Log4j2
@Service(value = "ticket")
@RequiredArgsConstructor
public class TicketsNoticeServiceImpl extends BaseGenericService implements NoticeService {

    private final TicketEntryService ticketEntryService;

    @Override
    public Mono<Void> sender(Integer tenant, CallbackMessage callbackMessage) {

        if (callbackMessage.getAction() == CallbackAction.deleted) {
            log.debug("Ticket wise send delte tenant id is:{} ,cw id is {}", tenant, callbackMessage.getId());
            TicketOnly ticketOnly = TicketOnly.builder()
                    .cwId(callbackMessage.getId())
                    .tenantId(tenant)
                    .action(callbackMessage.getAction())
                    .build();
            ticketOnly.setAction(callbackMessage.getAction());
            log.info("ticketOnly:11:cwid:" + ticketOnly.getCwId());
            this.messagingTemplate.convertAndSend("msp.wise.callback.tickets", "", ticketOnly);
            return Mono.empty().then();
        }

        return Mono.just(callbackMessage.getEntity()).map(str -> {
            try {
                log.debug("ticketOnly:22:callbackMessage:entity:" + callbackMessage.getEntity());
                return this.objectMapper.readValue(callbackMessage.getEntity(), JsonNode.class);
            } catch (JsonProcessingException e) {
                log.error("covert Call back str entity is error {}", e.getMessage());
                return this.objectMapper.createObjectNode();
            }
        }).flatMap(jsonNode -> this.onGetWiseProperties(tenant)
                .flatMap(configuration -> this.ticketEntryService.covertSetTicket(configuration, jsonNode))
                .doOnNext(ticketOnly -> {
                    log.debug("Ticket wise send tenant id is:{} ,cw id is {}", tenant, ticketOnly);
                    ticketOnly.setAction(callbackMessage.getAction());
                    this.messagingTemplate.convertAndSend("msp.wise.callback.tickets", "", ticketOnly);
                }).then());
    }


}
